package top.wardyan.wdev.dbdevassist.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.wardyan.wdev.dbdevassist.config.DDA;
import top.wardyan.wdev.dbdevassist.model.MasterModel;
import top.wardyan.wdev.dbdevassist.model.Proc;
import top.wardyan.wdev.dbdevassist.model.YTObject;
import top.wardyan.wdev.dbdevassist.service.ISysService;

public class SysServiceImpl<T extends MasterModel<T>> implements ISysService<T>{
	
	private T dao = null;
	
	public SysServiceImpl(T dao) {
		this.dao = dao;
	}

	@Override
	public List<T> list(int xType) {
		return this.list(xType, null);
	}

	@Override
	public List<T> listTableFunc(int xType) {
		return this.list(xType, "TF");
	}

	@Override
	public List<T> listFunc(int xType) {
		return this.list(xType, "FN");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public List<T> list(int xType, String type) {
		//long before = System.currentTimeMillis();
		//return dao.find("SELECT m.*, b.xHint, b.rOwner_ID, ISNULL(b.sStatus, 2) AS sStatus, b.sVersion FROM sys.procedures AS m LEFT JOIN dbo.yt_object AS b ON b.xName = m.name WHERE ISNULL(b.rType_ID, 0) IN (0, 10)");
		List<T> rs =  dao.find("SELECT m.* FROM " + dao.tableName() + " AS m " + (type != null ? "WHERE type = '" + type + "'" : ""));
		//System.out.println("111:" + (System.currentTimeMillis() - before));
		List<YTObject> objs = DDA.getInstance().objectService.list(xType);
		//System.out.println("222:" + (System.currentTimeMillis() - before));
		Map<String, YTObject> objmap = new HashMap<>();
		if(objs != null) {
			for(YTObject b : objs) {
				objmap.put(b.getXName(), b);
			}
		}
		//System.out.println("333:" + (System.currentTimeMillis() - before));
		if(rs != null && objs != null) {
			for(T c : rs) {
				YTObject obj = objmap.get(c.getStr("name"));
				c.put("sStatus", obj != null && obj.getSStatus() != null && obj.getSStatus().getSID() > 0 ? obj.getSStatus().getSID() : 2)
					.put("rOwner_ID", obj != null && obj.getROwnerID() != null && obj.getROwnerID().getSID() > 0 ? obj.getROwnerID().getSID() : 0)
					.put("xHint", obj != null && obj.getXHint() != null ? obj.getXHint() : "")
					.put("sVersion", obj != null && obj.getSVersion() > 0 ? obj.getSVersion() : 1);
			}
		}
		//System.out.println("总耗时:" + (System.currentTimeMillis() - before));
		return rs;
	}

	@Override
	public List<T> listTableType(int xType) {
		return this.list(xType, "TT");
	}

}
